package com.yunkeji.common.msg.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.ahocorasick.trie.Emit;
import org.ahocorasick.trie.Trie;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
/** 违禁词检测工具 */
public class BadWordDetectorUtils {

    public static String CHECK_URL = "http://172.16.88.64:8099";

    private Trie trie;

    public BadWordDetectorUtils(Set<String> badWords) {
        Trie.TrieBuilder builder = Trie.builder();
        for (String word : badWords) {
            builder.addKeyword(word);
        }
        this.trie = builder.build();
    }

    public boolean containsBadWord(String text) {
        Iterable<Emit> emits = this.trie.parseText(text);
        return emits.iterator().hasNext();
    }

    public Set<String> getBadWords(String text) {
        Iterable<Emit> emits = this.trie.parseText(text);
        List<Emit> emitList = new ArrayList<>();
        emits.forEach(emitList::add); // 将 Iterable 转换为 List
        return emitList.stream().map(Emit::getKeyword).collect(Collectors.toSet());
    }

    /**
     * 加强检测
     *
     * @author 老张
     */
    public static boolean checkAgain(String content) {
        try {
            String res =
                    HttpUtil.createPost(CHECK_URL + "/moderation/checkText.php")
                            .body(JSONUtil.createObj().set("content", content).toString())
                            .execute()
                            .body();
            log.info("违禁词检测结果:{}", res);
            return 0 != JSONUtil.parseObj(res).getInt("code");
        } catch (Exception e) {
            return false;
        }
    }
}
